<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('商品库')" />
	<th:block th:include="include :: businessCSS" />
	<style>
        .main-content{position: relative;}
		.preservationBtn{padding: 10px;margin: 0;position: fixed;top: 0;z-index: 9999;background: #fff;width: 100%;}
		.preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 5px;cursor: pointer;}
		/* .layui-border-box{height: 350px !important;}
		.layui-table-body{height: 240px !important;} */
		.layui-table-tool-temp{padding-right: 30px;}
        .getDetailUpload,.getDetailUpload2{cursor: pointer;}
        .layui-table-tool-self{display: none;}

	</style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
	<form class="layui-form head-form">
	    <div class="north" style="background-color: #fff;">
			<!-- <div class="layui-form-item preservationBtn">
                <button class="layui-btn layui-btn-normal dhicon" type="button" lay-submit lay-filter="btn-edit" id="btn-edit">保存</button>
                <button class="layui-btn layui-btn-normal dhicon" type="button" lay-submit lay-filter="btn-sh" id="btn-sh">审核</button>
                <button class="layui-btn layui-btn-normal dhicon" type="button" lay-submit lay-filter="btn-del" id="btn-del">删除</button>
			</div> -->
			<div style="width: 100%;height: 65px;background: #f6f6f6;"></div>
			<div class="forminput"></div>
    	</div>
    </form>
	</div>
</div>
<div style="width: 100%;height: 10px;background: #f6f6f6;"></div>
<div>
    <table class="layui-hide" id="mjdhtable" lay-filter="mjtable"></table>
    <script type="text/html" id="zjtoolbar">
        <div style="padding: 16px;display: flex;justify-content: space-between;">
            <div  style="font-weight: 700;font-size: 18px;">子件列表</div>
    		<div>
                <button class="layui-btn layui-btn-normal dhicon" lay-event="addbtn" id="btn-sh">新增</button>
                <button class="layui-btn layui-btn-danger dhicon" lay-event="mjbtn_save" id="btn-sh">删除</button>
    		</div>
    	</div>
    </script>
</div>

<!-- <div>
    <table class="layui-hide" id="zjdhtable" lay-filter="zjtable"></table>
    <script type="text/html" id="jptoolbar">
        <div style="padding: 16px;display: flex;justify-content: space-between;">
            <div  style="font-weight: 700;font-size: 18px;">子件列表</div>
    	</div>
    </script>
</div> -->
<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<!-- <th:block th:include="include :: inlineJS" /> -->

<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix = ctx + "business/productbasis",
    	prefix2 = ctx + "base/company";

	var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
	var fieldsHiddenList = [[${fieldsHiddenList}]];
	var moduleTable = [[${moduleTable}]];
	var enableEdit = [[${enableEdit}]];
    //母件表格基础信息
	// var gridColumns = [[${gridColumns}]];
    //母件表格基础信息
	var gridColumnsZJ = [[${gridColumnsZJ}]];
    // 母件列表数据
    var List=[[${List}]];
    //子件列表数据
    var sonList=[[${sonList}]];

	var $,layer,form,table;
    layui.use(['laydate','form','layer','jquery','util','element','upload','table'], function () {
        $ = layui.$,layer = layui.layer,form = layui.form,laydate = layui.laydate,util = layui.util,element=layui.element,upload = layui.upload,table = layui.table;
        beforeInit();//表单初始化之前的动作集合
		//初始化操作
        var code=""
		var str=`<div class="layui-form layui-card-header layuiadmin-card-header-auto">
		<div class="layui-form-item margin_t0">`
	    $.each(fieldsList,function(i,v){
            if(v.fields=='code')code=v.fieldContent
			if(enableEdit==1){
				str+=`<div class="layui-inline margin_r0 ${v.fieldFrontTopSize == 1 ?'layui-col-sm4':(v.fieldFrontTopSize == 2 ?'layui-col-sm8':'layui-col-sm12')}">
	    		    <label class="layui-form-label">`
					if(v.fieldFrontRequired){str+=`<font class="f_red">*</font>`}	
	    			str+=`<font>${v.fieldName}：</font>
	    		    </label>
	    		    <div class="layui-input-block">`
	    			if(v.fieldFrontType=='t_text')str+=`<input  type="text"  name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" class="${v.fieldFrontEdit ?'layui-input':'layui-input canntEdit'}" lay-verify="${v.fieldFrontRequired ?'required':''}" autocomplete="off" onblur="${v.fieldFrontRequired ?'inputOnBlur(this)':''}" ${v.fieldFrontEdit?'':'readonly'}>`
	    			if(v.fieldFrontType=='t_decimal')str+=`<input type="${v.fieldFrontEdit?'number':'text'}" value="${v.fieldContent}" name="${v.fields}" id="${v.fields}"  class="${v.fieldFrontEdit?'layui-input':'layui-input canntEdit'}" autocomplete="off"  onblur="${v.fieldFrontRequired?'inputOnBlur(this)':''}" ${v.fieldFrontEdit?'':'readonly'}>`
	    			if(v.fieldFrontType=='t_date' || v.fieldFrontType=='t_datetime' || v.fieldFrontType=='t_year' || v.fieldFrontType=='t_monthly'){
	    				str+=`<input type="text" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}"  datetype="${v.fieldFrontType}" class="${v.fieldFrontEdit ?'layui-input t_date' :'layui-input canntEdit'}" autocomplete="off"  onblur="${v.fieldFrontRequired?'inputOnBlur(this)':''}" ${v.fieldFrontEdit?'':'readonly'}>`
	    				str+=`<i id="${v.fields}_date" class="dhicon dh-calendar icon_date_business" style="font-size:0"></i>`
	    			}
                    if(v.fieldFrontType=='t_buttontext'){
                        str+=`<input type="text" class="${v.fieldFrontEdit ?'layui-input buttontext':'layui-input canntEdit'}" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" autocomplete="off" readonly onblur="${v.fieldFrontRequired?'inputOnBlur(this)':''}"/>`
                        if(v.fieldFrontEdit){
							str+=`<i class="layui-icon layui-icon-more getMore" onclick="getMore('${v.fields}',null,'${v.fieldName}','${v.fieldSearchType}',false,false)" getType="${v.fields}"></i>`
						}
                    }
                    if(v.fieldFrontType=='t_textarea')str+=`<textarea name="${v.fields}" id="${v.fields}" class="${v.fieldFrontEdit}?'layui-textarea':'layui-textarea canntEdit'" onblur="${v.fieldFrontRequired ?'inputOnBlur(this)':''}"  ${v.fieldFrontEdit?'':'readonly'}>${v.fieldContent}</textarea>`
					
	    			if(v.fieldFrontType=='t_file2'){
	    				str+=`<div class="layui-upload-drag fieldsimg" name="${v.fields}" id="${v.fields}_upimg">
	    					<input type="hidden" id="${v.fields}" name="${v.fields}" value="${v.fieldContent}"/>
	    					<div class="${v.fieldContent ?'layui-hide upicon':'upicon'}">
	    						<i class="layui-icon"></i>
	    						<p>点击上传图片</p>
	    					</div>
	    					
	    					<div class="${v.fieldContent ?'' :'layui-hide'}" id="uploadDemoView">
	    					  <img src="${v.fieldContent}" alt="上传成功后渲染" style="max-width: 196px">
	    					</div>.
	    				</div>`
	    			}
    
	    	        str+=`</div></div>`
			}else{
                str+=`<div class="layui-inline margin_r0 layui-col-sm4">
	    		    <label class="layui-form-label">`
					if(v.fieldFrontRequired){str+=`<font class="f_red">*</font>`}	
	    			str+=`<font>${v.fieldName}：</font>
	    		    </label>
	    		    <div class="layui-input-block">`
	    			
					if(v.fieldFrontType=='t_textarea'){
                        str+=`<textarea name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" class="layui-textarea canntEdit" readonly}></textarea>`
                    }else if(v.fieldFrontType=='t_file2'){
	    				str+=`<div class="layui-upload-drag fieldsimg" name="${v.fields}">
	    					<input type="hidden" id="${v.fields}" name="${v.fields}"/>
	    					<div class="${v.fieldContent ?'' :'layui-hide'}" id="uploadDemoView">
	    					  <img src="${v.fieldContent}" alt="上传成功后渲染" style="max-width: 196px">
	    					</div>.
	    				</div>`
	    			}else{
                        str+=`<input  type="text"  name="${v.fields}" id="${v.fields}" value="${v.fieldContent}" class="layui-input canntEdit" lay-verify="${v.fieldFrontRequired ?'required':''}" autocomplete="off" readonly>`
                    }
	    	        str+=`</div></div>`
            }
	    })
	    str+=`</div></div>`
        // 隐藏字段循环
		$.each(fieldsHiddenList,function(i,v){
             str+=`<input type="hidden" name="${v.fields}" id="${v.fields}" value="${v.fieldContent}">`
             if(v.fields=="vType"){
                if(v.fieldContent==2){
                    setTimeout(()=>{
                        $('button').attr('disabled',true)
                        $('button').css('background',"#bbb")
                    },500)
                }
             }
		})
	    $('.forminput').html(str)
        // 保存操作
        form.on('submit(btn-edit)', function(data){
            var is_return = false//是否中断保存
            fieldsList.map((v,i)=>{
                if(v.fieldFrontRequired){
                    if(!$('#'+v.fields).val()){
                         layer.msg(v.fieldName+'不能为空')
                         is_return=true
                    }
                }
            })
            if(is_return) return;
            $.modal.loading("正在处理中，请稍后...");
            listData1.map((v,i)=>{
                v.iid=i+1
            })
            listData2.map((v,i)=>{
                v.iid=i+1
            })
		    $.post("/purchase/purchaseplancancel/editpost",{infoMap:JSON.stringify(data.field),infoItems:JSON.stringify(listData1),sonData:JSON.stringify(listData2)},function(res){
                $.modal.closeLoading()
                layer.msg(res.msg);
                if(res.code == 0){
                    window.location.href = '/purchase/purchaseplancancel/edit?nid=' + res.data;
                }
                  
	        });
        });
        // 审核操作
        form.on('submit(btn-sh)', function(data){
            var nid=$('#nid').val()
            if(!nid|| nid==0){
                layer.msg('请先保存数据')
            }else{
                layer.confirm('是否确定审核', {btn : ['确定', '取消']}, function() {
                    // $.modal.loading("正在处理中，请稍后...");
                    $.post("/purchase/purchaseplancancel/updateType",{nid,vType:2},function(res){
                        // $.modal.closeLoading()
				        layer.msg(res.msg);
                        if(res.code==0){
                            $('button').attr('disabled',true)
                            $('button').css('background',"#bbb")
                        }
                        
	                });
                });
                
            }
        });
        form.on('submit(btn-del)', function(data){
            var nid=$('#nid').val()
            if(!nid || nid==0){
                layer.msg('请先保存数据')
            }else{
                layer.confirm('是否确定删除', {btn : ['确定', '取消']}, function() {
                    $.modal.loading("正在处理中，请稍后...");
                    $.get("/purchase/purchaseplancancel/delete",{nid},function(res){
                        $.modal.closeLoading()
				        layer.msg(res.msg);
                        if(res.code==0){
                            window.location.href = '/purchase/purchaseplancancel/edit?nid=0';
                        }
	                });
                });
                
            }
        });

        
        var listData1=List ?List:[]
        var listData2=sonList ?sonList:[]
        // 初始化表格
            $.tablelist.init({
                elem: '#mjdhtable'
                ,data: listData1
                , page: false
                , even: true
                , limit: 10000
                , totalRow: gridColumnsZJ.totalRow
                , cols: [gridColumnsZJ.gridBody]
                , toolbar: '#zjtoolbar'
                , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                , height: '320'
                , done: function (res, curr, count) {
                    listData1 = table.cache.mjdhtable;//每次重载都赋值更新表缓存
                },success:function(a,b,c){
                }
            });
            // $.tablelist.init({
            //     elem: '#zjdhtable'
            //     , data: listData2
            //     , page: false
            //     , even: true
            //     , limit: 10000
            //     , totalRow: gridColumnsZJ.totalRow
            //     , cols: [gridColumnsZJ.gridBody]
            //     , toolbar: '#jptoolbar'
            //     , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            //     , height: '300'
            //     , done: function (res, curr, count) {
            //         listData2 = table.cache.zjdhtable;//每次重载都赋值更新表缓存
            //     }
            // });

        //母件表格操作
        table.on('toolbar(mjtable)', function (obj) {
            var selectedObject=""
            table.cache.mjdhtable.map((v,i)=>{
                if(selectedObject){
                    selectedObject+=','+v.spBm
                }else{
                    selectedObject+=v.spBm
                }
            })
            switch (obj.event) {
                case 'addbtn':
			    layer.open({
                	type: 2,
                	area: [($(window).width() - 200)+'px', ($(window).height() - 100)+'px'],
                	fix: false,//不固定
                	offset: '10%',//距离顶部
                	maxmin: true,//最大最小化
                	shade: 0.3,//遮罩
                	title: '母件列表',
                	content: "/purchase/purchaseplan/select2?pagetype=checkbox&by=direct&fmoduleTable="+moduleTable+"&selectedObject="+selectedObject,
                	btn: ['确定', '取消'],
                	shadeClose: true,// 弹层外区域关闭
                	yes: function(index, layero){
						var res = window["layui-layer-iframe" + index].callbackdata();
				        if(res.length > 0){
                            var pcode=""
				        	$.each(res,function(i,v){
                                if(pcode){
                                    pcode+=','+v.spBm
                                }else{
                                    pcode+=v.spBm
                                }
				        	})
							layer.closeAll();
							listData1=res
							table.reload('mjdhtable', {data:listData1});
                           
				        	$.get('/purchase/purchaseplan/listzj2?fBm='+pcode, function(res){
                                listData2=res.data
                                table.reload('zjdhtable', {data:listData2});
				        	});
				        }else{
                            layer.msg("请选择数据");
                        }
                	}
                });

                   break;
    
                case 'mjbtn_save':
                    var objdata=table.checkStatus('mjdhtable')
                    objdata=objdata.data
                    listData1= table.cache.mjdhtable;
                    listData2 = table.cache.zjdhtable;
                    if(objdata.length>0){
                        objdata.forEach(item => {
                            listData1 = listData1.filter(items => items.spBm!= item.spBm);
                        });
                        objdata.forEach(item => {
                            listData2 = listData2.filter(items => items.fBm!= item.spBm);
                        });
                        table.reload('mjdhtable', {data:listData1});
                        table.reload('zjdhtable', {data:listData2});
                    }else{
                        layer.msg("请选择数据");
                    }
                    break;
            };
        });

        // 删除
        form.on('submit(btn_save)', function (data) {
            let cols=gridColumnsZJ.gridBody
            var required=[]
            $.each(cols, function (i, v) {
                var title=v.title
                if(title){
				    if(title.indexOf('<font class="f_red">*</font>') > -1){
                        required.push(v.field)
                    }
                }  
			})
            var isjx=true
            $.each(table.cache.zjdhtable, function (i, v) {
                v.guid=guid
				v.pcode=code
                for(var n=0;n<required.length;n++){
                    var fild=required[n]
                    if(!v[fild]){
                        isjx=false
                    } 
                }
			})
            if(!isjx) return layer.msg('请填写必填项');

            $.operate.post(prefix + "/savejppost", {'pcode':code,'productBasisCompeteItems': JSON.stringify(table.cache.zjdhtable),}, function (res) {
                if (res.code == 0){
					layer.msg(res.msg);
				}
            });
        });

        $(".fieldsimg").each(function(){
	    	var id=$(this).attr('name')
            upload.render({
                elem: '#'+id+'_upimg',
	            url: '/system/fileinfo/uploadmailimg',
	            accept: 'images',
	    		before: function(obj){
                    //预读本地文件示例，不支持ie8
                    obj.preview(function(index, file, result){
                      console.log(index, file, result)
                    });
                },
	            done: function (res) {
                    //如果上传失败
                    if (res.errno > 0) {
                        return layer.msg('上传失败');
                    }else{
	    				layer.msg('上传成功');
	    				$('#'+id).val(res.data[0])
	    				layui.$('#'+id+'_upimg').find('.upicon').addClass('layui-hide')
	    				layui.$('#'+id+'_upimg').find('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', res.data[0]);
	    			}
                },error: function (err) {
                    //演示失败状态，并实现重传
	            	console.log(err)
                }
            });
        })


		$('.t_date').each(function(){
            var datetype=$(this).attr('datetype')
            laydate.render({
				elem:this
                ,type: datetype=='t_date'?'date':datetype=='t_datetime'?'datetime':datetype=='t_year'?'year':'month'
			})
		})

    });
    

</script>

</body>
</html>